import { Button, Input, Menu, message, Modal, Spin } from 'antd';
import MenuOutLined from '@ant-design/icons/MenuOutlined'
import Player from 'renderer/components/Player';
import logo from '../../../../assets/logo.jpg'
import DB, { IDownloadDBTask, IHistory } from 'model/DB';
import { getFileNameByUrl } from 'renderer/utils/helps';
import { LoadType, TaskStatus, TSStatus } from 'renderer/constants/Consts';
import useGlobal from 'renderer/hooks/useGlobal';
import { useEffect, useState } from 'react';
import { CloudDownloadOutlined, ImportOutlined, SettingFilled} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import moment from 'moment';
import TabBtn from 'renderer/components/TabBtn';
import './Home.less';

// const { Search } = Input

const M3u8Protocol = ['http:','https:']

type MenuType = 'course' | 'download' | 'system' | 'out'


// const filterTaskByName = async (task: IDownloadDBTask[]) => {
//   tasks.forEach()
// }


// todo 记录每个课程播放进度，下次播放课程时，直接进入上次播放位置

export default function Home() {

  const navigate = useNavigate()

  const { taskList, playTask, playHistory, addTask, playCourse, updateCourse } = useGlobal()

  const [ m3u8Url, setM3U8Url ] = useState('')
  const [ loading, setLoading ] = useState(false)

  const [ pageLoading, setPageLoading ] = useState(false)

  const [ moreVisible, setMoreVisible ] = useState(false)

  const handleMenuClick = ({key}: {key: string}) => {
    if(key === "import") {
      // 卸载程序，重新安装后，会丢失之前的课程数据
      Modal.confirm({
        title: "导入本地课程",
        content: `只支持通过该程序下载的课程导入！`,
        className: 'global-confirm-modal',
          onOk: async () => {
            const path = await window.electron.ipcRenderer.getDirectory()

            if(path) {
              setPageLoading(true)
              const tasks = await window.electron.ipcRenderer.importLocalCourse(path)

              let hasImport = false
              tasks.forEach(async (task, index) => {
                // 判断该课程是否已在数据库中，如果已存在，则排除
                const findTask = await DB.downloadTasks.where('name').equals(task.name).first()
                if(!findTask) {
                  // 将该课程写入数据库 不记录该课程之前的id
                  const { id, ...taskData } = task
                  const newTask = {...taskData, loadType: LoadType.Import}
                  const taskId = await DB.downloadTasks.add(newTask)

                  hasImport = true;

                  window.electron.log.info('import task: ', newTask)
                }

                if(index === tasks.length - 1) {
                  if(hasImport) {
                    // 将当前路径作为本地服务的静态资源路径，并且存储到缓存中
                    window.electron.ipcRenderer.setStaticPath(path)

                    message.info("课程导入成功，可在 '下载管理/已下载' 中进行查看")
                  } else {
                    message.warn('该目录下未找到已下载的可导入课程！')
                  }
                }

              });

            } 

            setPageLoading(false)
          }
      })
    } else {
      navigate(key, {replace: true})
    }
    

    // 0412注释该功能
    // updateCourse(undefined)
  }

  // 下载 m3u8
  const handleDownloadFile = async () => {

    if(m3u8Url === '') {
      return
    }

    // 解析地址 设置任务参数
    const { protocol, pathname, origin, searchParams } = new URL(m3u8Url)

    const title = searchParams.get('title')
    const sub_title = searchParams.get('sub_title')
    const course_id = searchParams.get('course_id')
    const sub_id = searchParams.get('sub_id')

    const url = origin + pathname


    // 唯一 m3u8 文件路径名
    const fileName = window.electron.crypto.md5(m3u8Url)
    // console.log('filename =', fileName)

    // 判断地址是否符合
    if(!M3u8Protocol.includes(protocol) || !m3u8Url.includes('.m3u8')) {
      message.warn('课程地址不符合要求')
      return
    } else if(title === '' || sub_title === '' || course_id === '' || sub_id === '') {
      message.warn('课程地址确实参数')
      return
    }

    // 判断有没有重复下载
    const findTask = await DB.downloadTasks.where('name').equals(fileName).first()
    if(findTask) {
      message.warn('该课程已下载')
      return
    }

    try {

      // 首先获取下载路径，第一次会提示设置，后面如果不主动改变，则以上次路径
      let savePath = await window.electron.ipcRenderer.getStoreValue('save-path')

      if(!savePath) {
        // 如果没有，则提示用户设置
        savePath = await window.electron.ipcRenderer.setSavePath()
      }

      const testpath = window.electron.path.resolve(savePath, fileName)
      // console.log('savePath ==', savePath,fileName, testpath)

      setLoading(true)

      // 根据当前路径 创建下载任务
      const filePath = window.electron.path.resolve(savePath, fileName) //savePath + '\\' + fileName
      const m3u8Path = window.electron.path.resolve(filePath, 'index.m3u8') //filePath +'\\' + 'index.m3u8'
      const m3u8 = await window.electron.ipcRenderer.startDownloadM3U8({url, filePath: m3u8Path, fileName})

      // 开启 ts 文件下载
      if(m3u8 === undefined) {
        setLoading(false)
        message.error('课程下载失败，m3u8文件错误')

      } else {
        setLoading(false)
        setM3U8Url('')

        message.info('下载地址已添加到下载列表')
        // console.log('m3u8 =', parser.manifest)
        let duration = 0;
        m3u8.segments.forEach(item => duration = duration + item.duration)

        const task = {
          url,
          localUrl: `/${fileName}/index.m3u8`,
          name: fileName,
          path: m3u8Path,
          title: title !== null ? title : '',
          sub_title: sub_title !== null ? sub_title : '',
          course_id: course_id !== null ? parseInt(course_id) : 0,
          sub_id: sub_id !== null ? parseInt(sub_id) : 0,
          // 新添加的任务，默认都是待下载
          status: TaskStatus.Waiting,
          tsCount: m3u8.segments.length,
          downloadCount: 0,
          duration,
          completeTime: '',
          createTime: moment().format('YYYY-MM-DD hh:mm:ss'),
          loadType: LoadType.Download
        }
        // console.log('task =', task)
        // 数据库写入 m3u8 课程下载任务数据
        const taskId = await DB.downloadTasks.add(task)

        const files = m3u8.segments.map(item => {
          // 判断 uri 上是不是全路径，如果是，则补充，如果不是，则需要将m3u8的路径补充进去
          const url = item.uri.indexOf('/') === 0 ? origin + item.uri : origin + pathname.substring(0, pathname.lastIndexOf('/')+1) + item.uri
          const name = getFileNameByUrl(url)
          // const tsFile = filePath + '\\' + name + '.ts'
          const tsFile = window.electron.path.resolve(filePath, `${name}.ts`)

          return {
            taskId,
            url,
            path: tsFile,
            name,
            duration: item.duration,
            pathname: item.uri,
            status: TSStatus.Waiting
          }
        })

        // 数据库写入 ts 文件下载数据
        const key = await DB.downloadFiles.bulkAdd(files)
        // console.log('key =', key)

        // 设置下载任务
        addTask({...task, id: taskId}, files)

      }

    } catch (error) {
      setLoading(false)
      console.log('download m3u8 error:', error)
      message.warn('课程下载错误！')
    }


  }

  // 播放
  const handlePlayClick = async (task: IHistory) => {
    playCourse(task)
  }

  // 进入程序后，开启默认下载
  useEffect(() => {

    const autoDownload = async () => {
      const tasks = await DB.downloadTasks.where('status').equals(TaskStatus.Downloading).toArray()
      // 将正在进行中的任务，全部设置为 等待下载中
      // console.log('tasks ==', tasks)
      if(tasks.length > 0) {
        // 第一个任务进行自动下载
        const task = tasks.shift()
        // 开始自动下载
        const files = await DB.downloadFiles.where({taskId: task!.id!})
                              .and(function(account){
                                return account.status !== TSStatus.Done
                              })
                              .toArray()
        // console.log('files ==', files)
        addTask(task!, files)

        // 更新数据库数据
        tasks.forEach(item => {
          // DB.downloadFiles.where({id: item.id!}).modify({status: TaskStatus.Waiting})
          DB.downloadTasks.put({
            ...item,
            status: TaskStatus.Waiting
          })
        })
      } else {
        // 取第一个等待下载的任务进行下载
        const task = await DB.downloadTasks.where('status').equals(TaskStatus.Waiting).first()
        if(task) {
          const files = await DB.downloadFiles.where({taskId: task!.id!})
                                .and(function(account){
                                  return account.status !== TSStatus.Done
                                })
                                .toArray()
          // console.log('files ==', files)
          addTask(task!, files)

        }
      }
    }

    autoDownload()

    // DB.downloadTasks.where({id: 37}).modify({course_id: 30496, sub_id: 722178})

  }, [])

  const loadingTask = taskList.find(item => item.status === TaskStatus.Downloading)

  // console.log('taskList ==', taskList, loadingTask)

  return (
    <div className='page-home' >
      <div className='home-header' >
        <div className='home-header-left' >
          <img className='login' src={logo} />
          <div className='download-search' >
            {/* <Search placeholder='请输入下载的视频地址' onSearch={handleDownloadFile} /> */}
            <Input placeholder='请输入下载的视频地址'
              size='large'
              className='download-input'
              value={m3u8Url}
              onChange={e => setM3U8Url(e.target.value)}
              // onPressEnter={handleDownloadFile}
            />
            <Button type='primary'
              className='download-btn'
              loading={loading}
              onClick={handleDownloadFile}
            >课程视频下载</Button>
          </div>
        </div>
        <div className='home-header-right' >
          <Button type='link' size='large' icon={<MenuOutLined />} onClick={() => setMoreVisible(!moreVisible)} />
        </div>
      </div>
      <div className='home-contenxt' >
        <div className='home-player'>
          <Player />
        </div>
        <div className='home-content-right'>
          {!moreVisible && <div className='home-history-list'>
            {playHistory.map(item => <TabBtn key={item.taskId}
              select={playTask?.taskId === item.taskId}
              onClick={() => handlePlayClick(item)}
            >{`${item.title}-${item.sub_title}`}</TabBtn>)}
          </div>}
          {moreVisible && <Menu mode='vertical' className='home-menu' onClick={handleMenuClick} >
            {/* <Menu.Item key="course" icon={<PlaySquareFilled />} >课程视频管理</Menu.Item> */}
            <Menu.Item key="/download" icon={<CloudDownloadOutlined />} >下载管理</Menu.Item>
            <Menu.Item key="import" icon={<ImportOutlined size={16} />} >导入本地课程</Menu.Item>
            <Menu.Item key="/setting" icon={<SettingFilled />} >系统设置</Menu.Item>
          </Menu>}
        </div>
      </div>
      <div className='home-footer'>
        <div>
          正在播放
          <span>{playTask ? `: ${playTask.title}-${playTask.sub_title}` : ''}</span>
        </div>
        <div>
          正在下载课程
          <span>{loadingTask ? `: ${loadingTask.title}-${loadingTask.sub_title}` : ''}</span>
        </div>

      </div>

      {pageLoading && <div className='home-page-loading'>
        <Spin tip="课程导入中......" size='large' />
      </div>}

    </div>
  )
}
